//
//  WCNCareRecordAddVC.m
//  WCN
//
//  Created by 杨鑫 on 15/6/30.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNCareRecordAddVC.h"
#import "WCNMulTextEditVC.h"
//
#import "WCNMulTextTCell.h"
#import "WCNCareRecordEditTCell.h"
#import "WCNCareRecordItemTCell.h"
#import "WCButton.h"
#import "WCDrawBorderView.h"
#import "WCNCareRecordDetailFooterView.h"
#import "WCImgBrowserView.h"
#import "WCPickerView.h"
#import "LCActionSheet.h"
//
#import "UILabel+Utilities.h"
#import "NSDate+Utilities.h"
#import "NSString+Utilities.h"
#import "UINavigationItem+Offset.h"
//
#import "WCDefaultManager.h"
#import "WCImageManager.h"
#import "WCPopupLayerManager.h"
#import "WCNetworkAccessManager.h"
#import "WCNPListFileDataStore.h"
#import "Patient.h"
//
#import "Macros.h"
#import "Constants.h"
#import "WSJHorTableView.h"
#import "JCAlertView.h"
#import "WCImageView +setImage.h"
#import "WCNParentCareRecordVC.h"
#import "UIImage+WebP.h"
#import "WCNWoundDrugView.h"
#import "WCNWoundDealCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "WCNWoundDesCell.h"
#import "WSJWoundDesVC.h"
#import "WSJTwoLevelPicker.h"
#import "JCAlertView.h"
#import "WCNAddWoundDesCell.h"
#import "WSJImage.h"
#import "WoundRecord.h"
#import "UMMobClick/MobClick.h"

static const int kMaxInputLength = 5;
static NSString *cellId = @"WCNMulTextTCell";
static NSString *cellId2 = @"WCNCareRecordEditTCell";
static NSString *cellId3 = @"WCNCareRecordItemTCell";
static NSString *cellId4 = @"WCNWoundDealCell";

@interface WCNCareRecordAddVC ()<UITableViewDataSource, UITableViewDelegate, LCActionSheetDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIAlertViewDelegate,UITextFieldDelegate>

@property (strong, nonatomic) Patient *patient;
@property (strong, nonatomic) NSMutableDictionary *data;
@property (strong, nonatomic) NSArray *drugs;
@property (strong, nonatomic) NSMutableArray *deals;



@property (strong, nonatomic) UITableView *tableView;

@property (weak, nonatomic) UIView *footerView;
@property (weak, nonatomic) UIButton *addBtn;


//以供选择的数据
@property (strong, nonatomic) NSArray *offerDrugs;
//护理用品类型
@property (strong, nonatomic) NSMutableArray *careProductions;

//根据已选的药品查询处理方案
@property (strong, nonatomic) NSArray *selectedDrugs;
@property (strong, nonatomic) NSMutableDictionary *offerDeals;
@property (strong, nonatomic) NSString *getDealsUrl;
//选择的图片
@property (strong, nonatomic) NSArray *selImages;

@property (nonatomic,  strong) WCButton *saveBtn;

@property (nonatomic,  strong) WSJHorTableView *picTableView;
//已经上传的图片
@property (nonatomic,  strong) NSMutableArray *webImages;
// 当前模式
@property (nonatomic,  assign) WCNCareRecordAddVCType type;


@property (nonatomic,  strong) NSMutableArray <NSURLSessionDataTask *> *uploadTasks;

@property (nonatomic,  strong) MBProgressHUD *hud;

@end

@implementation WCNCareRecordAddVC

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"--------------WCNCareRecordAddVC-------------------");
    self.selImages = nil;
    self.picTableView = nil;
    self.webImages = nil;
}


- (instancetype)initWithPatient:(id)patient wound:(WoundRecord *)wound type:(WCNCareRecordAddVCType)type
{
    self = [super init];
    if (self) {
        self.title = @"伤口护理记录";
        _type = type;
        _patient = patient;
        _data = [NSMutableDictionary dictionary];
        _drugs = [NSMutableArray array];
        _deals = [NSMutableArray array];
        _data[@"bodyPartCode"] = wound.bodyPartCode;
        _data[@"bodyPartName"] = wound.bodyPartName;

        _data[@"description"] = wound.woundDescription;

        
        //        _selImages = [NSMutableArray array];
    }
    return self;
}


- (instancetype)initWithData:(id)data type:(WCNCareRecordAddVCType)type
{
    self = [self initWithPatient:nil wound:nil type:type];
    if (self) {
//        self.title = @"伤口护理记录";
        
//        _drugs = [data[@"medicines"] copy];
//        _deals = [data[@"treatments"] copy];
        NSMutableArray *muDrugs = [data[@"medicines"] mutableCopy];
        for (int i = 0; i < muDrugs.count; i++) {
            NSMutableDictionary *muDrug = [muDrugs[i] mutableCopy];
            for (NSDictionary *deal in data[@"treatments"]) {
                if ([deal[@"medicineId"] isEqual:muDrugs[i][@"id"] ]) {
                    NSMutableArray *muArr = [muDrug[@"treatments"] mutableCopy];
                    if (!muArr) {
                        muArr = [NSMutableArray array];
                    }
                    [muArr addObject:deal];
                    muDrug[@"treatments"] = [muArr copy];
                }
            }
            muDrugs[i] = muDrug;
        }
        _drugs = [muDrugs copy];
        _data = [NSMutableDictionary dictionaryWithDictionary:data] ;
        
    }
    return self;
}


- (NSMutableArray<NSURLSessionDataTask *> *)uploadTasks{
    if (!_uploadTasks) {
        _uploadTasks = [NSMutableArray array];
    }
    return _uploadTasks;
}

#pragma mark -没get一次选择的照片 都从 cell里去取
- (NSArray *)selImages{
    
    _selImages =self.picTableView.currentPics;
    return  _selImages;
}
- (instancetype)initWithPatient:(id)patient withWound:(WoundRecord *)wound withTask:(NSMutableDictionary *)task type:(WCNCareRecordAddVCType)type
{
    self = [self initWithPatient:patient wound:(id)wound type:type];
    
    _data = [task mutableCopy];
    _drugs = [_data[@"medicines"] mutableCopy];
    _deals = [_data[@"treatments"] mutableCopy];
    
    [_data setValue:nil forKey:@"medicines"];
    [_data setValue:nil forKey:@"treatments"];
  
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    WCButton *rightBtn = [WCButton wcButtonWithType:WCButtonTypeSave];
    [rightBtn addTarget:self action:@selector(save:) forControlEvents:UIControlEventTouchUpInside];
    self.saveBtn = rightBtn;
    [self.navigationItem addRightBarButtonItem:rightBtn];
    
    
    [self.tableView registerNib:[UINib nibWithNibName:cellId bundle:nil] forCellReuseIdentifier:cellId];
    [self.tableView registerNib:[UINib nibWithNibName:cellId2 bundle:nil] forCellReuseIdentifier:cellId2];
    [self.tableView registerNib:[UINib nibWithNibName:cellId3 bundle:nil] forCellReuseIdentifier:cellId3];
    [self.tableView registerNib:[UINib nibWithNibName:cellId4 bundle:nil] forCellReuseIdentifier:cellId4];
    [self.tableView registerNib:[UINib nibWithNibName:@"WCNAddWoundDesCell" bundle:nil] forCellReuseIdentifier:@"WCNAddWoundDesCell"];
    
    WCDrawBorderView *tableHeaderView = [[WCDrawBorderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 15)];
    tableHeaderView.borderColor = kBorderColor;
    tableHeaderView.bottomBorder = YES;
    tableHeaderView.backgroundColor = [UIColor clearColor];
    
    self.tableView.tableHeaderView = tableHeaderView;
    switch (self.type) {
        case WCNCareRecordAddVCTypeScan:{
            self.title = @"护理记录";
            rightBtn.hidden = YES;
            [self getImageWithUrls:self.data[@"images"]];
        }
            break;
        case WCNCareRecordAddVCTypeAdd: {
            self.title = @"添加护理记录";
            UIView *tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 130)];
            [self loadFooterView:tableFooterView];
            self.tableView.tableFooterView = tableFooterView;
        }
            
            break;
            
        case WCNCareRecordAddVCTypeEdit: {
            self.title = @"编辑护理记录";
            if ([self.data[@"images"] count] == 0) {
                UIView *tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 130)];
                [self loadFooterView:tableFooterView];
                self.tableView.tableFooterView = tableFooterView;
            }else {
                
                [self getImageWithUrls:self.data[@"images"]];
            }
        }
            break;


        default:
            break;
    }
    
}
- (UITableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.backgroundColor = kAppBg;
        _tableView.showsVerticalScrollIndicator = NO;
        [self.view addSubview: _tableView];
    }
    return  _tableView;
}

- (void)pageBack
{
    
   
    if (self.type == WCNCareRecordAddVCTypeScan) {
        [self.navigationController popViewControllerAnimated:YES];
    }else {
    
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"护理记录尚未保存!"
                                                           delegate:self
                                                  cancelButtonTitle:@"放弃"
                                                  otherButtonTitles:@"继续", nil];
        alertView.tag = 1;
        [alertView show];
    
    }
}


-(void)getImageWithUrls:(NSArray *)urls
{
    _webImages = [NSMutableArray array];
    NSString *path =[[NSBundle mainBundle] pathForResource:@"config" ofType:@"plist"];
    NSDictionary *plistDict =[NSDictionary dictionaryWithContentsOfFile:path];
    NSString *priod = plistDict[@"MODEL"];
    NSString *bathUrl =[plistDict[@"MEDIAS"] objectForKey:priod];
    [urls enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (!*stop) {
            
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSString *newStr =[NSString stringWithFormat:@"%@%@%@",bathUrl,@"/image/simg/",obj];
                NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:newStr]];
                UIImage *image = [UIImage imageWithData:data];
                WSJImage *wimage =[WSJImage new];
               
                if (image) {
                     wimage.bigImage =image;
                    [_webImages addObject:wimage];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (_webImages.count == urls.count) {
                        UIView *tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 130)];
                        [self loadFooterView:tableFooterView];
                        self.tableView.tableFooterView = tableFooterView;
                    }
                });
            });

        }
    }];
    
}


#pragma mark - 加载底部图片编辑

- (void)loadFooterView:(UIView *)tableFooterView
{
    WCDrawBorderView *view1 = [[WCDrawBorderView alloc] initWithFrame:CGRectMake(0, -kOnePX, kScreenWidth, 45+kOnePX)];
    view1.topBorder = YES;
    view1.borderColor = kBorderColor;
    view1.backgroundColor = [UIColor whiteColor];
    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(14, 10, 200, 25)];
    label1.font = [UIFont systemFontOfSize:16.0];
    label1.text = @"伤口图片";
    UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth-11-13, 16, 13, 13)];
    imageView1.image = [UIImage imageNamed:@"Arrow_Down"];
    [view1 addSubview:label1];
    [view1 addSubview:imageView1];
    
    
    WCNCareRecordDetailFooterView *footerView = [[WCNCareRecordDetailFooterView alloc] initWithFrame:CGRectMake(0, 40, kScreenWidth, 90)];
    WSJHorTableView *picTableView =[[WSJHorTableView alloc] initWithFrame:CGRectMake(0, 10, kScreenWidth, 65)];
    self.picTableView = picTableView;
    picTableView.dateArray = [self.webImages mutableCopy];
    if (self.type == WCNCareRecordAddVCTypeScan) {
        picTableView.type = 1;
        picTableView.imageUrls = self.data[@"images"];
        
    }else {
        
        picTableView.type = 0;
    }
    //picTableView.imageUrls =images;
    defineWeakSelf;
    picTableView.presentDelegate = ^(){return weakSelf;};
    [footerView addSubview:picTableView];
    self.footerView = footerView;
    
    [tableFooterView addSubview:view1];
    [tableFooterView addSubview:footerView];
}

#pragma mark - 选择图片

- (void)addImage
{
    LCActionSheet *sheet = [LCActionSheet sheetWithTitle:nil buttonTitles:@[@"拍照", @"相册"] redButtonIndex:-1 delegate:self];
    [sheet showInView:self.navigationController.view];
}



#pragma mark - 保存数据

- (void)save:(UIButton *)btn
{
    NSString *bodyPartCode = self.data[@"bodyPartCode"];
    if (!bodyPartCode) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"请选择伤口部位" withView:self.view];
        return;
    }
    
    NSString *targetDay = self.data[@"targetDay"];
    if (!targetDay) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"请选择伤口天数" withView:self.view];
        return;
    }
    
    //如果事编辑模式  直接上传 并返回
    if (self.type == WCNCareRecordAddVCTypeEdit) {
        [self startUploadImages];
        return;
    }
    //如果事添加模式 继续执行
    WCNetworkAccessManager *netWork = [WCNetworkAccessManager sharedMg];
    if (netWork.netStatus == NetworkStatusWIFI || netWork.netStatus == NetworkStatus4G) {
        [self startUploadImages];
        
    } else {
        if (netWork.netStatus == NetworkStatusUnknow || netWork.netStatus == NetworkStatusNO) {
            
            [JCAlertView showOneButtonWithTitle:@"提示" Message:@"暂时没有网络,将缓存到本地~" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"好的" Click:^{
                [self saveToLocal];
            }];
            
        } else {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                message:@"当前处在非Wi-Fi或4G网络下，您确定上传图片吗？"
                                                               delegate:self
                                                      cancelButtonTitle:@"取消"
                                                      otherButtonTitles:@"确认", nil];
            alertView.tag = 0;
            [alertView show];
        }
    }
}


- (void)startUploadImages
{
    
    if (self.selImages.count == 0) {
        
        [self startUploadAll:nil toLocal:NO];
        return;
    }
    NetworkStatus state = [WCNetworkAccessManager sharedMg].netStatus;
    if ( state == NetworkStatus2G || state == -1) {
        defineWeakSelf;
        [JCAlertView showTwoButtonsWithTitle:@"提示" Message:@"您使用的是2g网络,建议缓存在本地,等待wifi环境继续上传~" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"继续上传" Click:^{
            [weakSelf normalUpload];
        } ButtonType:JCAlertViewButtonTypeWarn ButtonTitle:@"缓存本地" Click:^{
             [weakSelf saveToLocal];
        }];
       
    }else{
     [self normalUpload];
    
    }
   
}

- (void)normalUpload{
    
    self.saveBtn.enabled = NO;
    __block NSArray *temArray;
    __block NSInteger isFailue = 0;;
    defineWeakSelf;
    
    //    hud.progress = 0;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        temArray = weakSelf.selImages;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.saveBtn.enabled = YES;
            [JCAlertView showTwoButtonsWithTitle:@"提示" Message:@"是否确认上传图片,请一次上传不要超过8张" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"否" Click:^{
                
            } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确认" Click:^{
                //上传图片
                
                
                
                
                //                [CoreSVP showProgess:progress Msg:@"上传进度..." maskType:SVProgressHUDMaskTypeClear];
                __weak MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:self.view animated:YES];
                weakSelf.hud = hud;
                //    hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
                hud.animationType = MBProgressHUDAnimationZoomIn;
                //    hud.labelText = @"正在下载...";
                
                //------------------------------------
                __block NSInteger sucessTag = 0;
                NSMutableArray *namesArray =[NSMutableArray array];
                hud.labelText = [NSString stringWithFormat:@"1/%i",temArray.count];
                for (int i =0; i<temArray.count; i++) {
                    NSURLSessionDataTask *task = [[WCImageManager sharedMg] uploadImage:@[temArray[i]] multi:NO progress:^(NSProgress *progress) {
                        
                    } success:^(NSDictionary *result){
                        //
                        sucessTag ++;
                        
                        
                        hud.labelText = [NSString stringWithFormat:@"%d/%i",sucessTag,temArray.count];
                        
                        NSString * imageId =result[@"data"][@"name"];
                        if (imageId) {
                            [namesArray addObject:imageId];
                        }
                        
                        if (sucessTag ==temArray.count) {
                            [weakSelf startUploadAll:namesArray toLocal:NO];
                        }
                        
                    } failure:^(NSString *msg){
                        
                        if (isFailue==0) {
                            isFailue =1;
                            [JCAlertView showOneButtonWithTitle:@"提示" Message:@"上传失败" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"知道了" Click:nil];
                        }
                        
                     
                        
                        if (isFailue ==1) {
                            [weakSelf saveToLocal];
                            
                            isFailue = 2;//保证只保存到本地一次
                        }
                    }];
                    [weakSelf.uploadTasks addObject:task];
                    
                }
                
            }];
            
        });
        
    });

}



- (void)saveToLocal
{
    weakSelf_define;
    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showWithLabel:@"缓存护理记录中..." withView:self.view];
    NSString *timeString = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
    //保存图片到本地, 时间+顺序作为文件名
    NSInteger index = 0;
    NSMutableArray *imageNames = [NSMutableArray array];
    for (UIImage *image in self.selImages) {
        NSString *imageName = [NSString stringWithFormat:@"%@+%ld", timeString, (long)index++];
        [[WCImageManager sharedMg] saveImageWaitUpload:image byName:imageName];
        [imageNames addObject:imageName];
    }
    
    [weakSelf startUploadAll:imageNames toLocal:YES];
    [hud hide:YES];
    
    [weakSelf.navigationController popViewControllerAnimated:YES];
    //保存后发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:CareRecordsRefreshNotification object:nil];
}

- (void)startUploadAll:(NSArray *)imageNames toLocal:(BOOL)local
{
    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:self.view];
    
    NSMutableDictionary *careData = [NSMutableDictionary dictionaryWithDictionary:self.data];
    careData[@"type"] = @"WOUND_NURSING_RECORD";
    careData[@"uploadBy"] = [[WCDefaultManager shareMg] account].stringId;
    careData[@"uploadTime"] = [[NSDate date] stringWithFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    //加载药瓶
    NSMutableArray *drugs = [self.drugs mutableCopy];
    //加载药品处理
    NSMutableArray *deals = [NSMutableArray array];
    for (int i = 0; i < drugs.count; i++) {

        NSMutableDictionary *muDict = [drugs[i] mutableCopy];
        if (muDict[@"treatments"]) {
            [deals addObjectsFromArray:muDict[@"treatments"]];
            [muDict removeObjectForKey:@"treatments"];
            drugs[i] = muDict;
        }
    }
    careData[@"medicines"] = drugs;
    careData[@"treatments"] = deals;
    
    if (imageNames && imageNames.count > 0) {
        careData[@"images"] = imageNames;
    }else {
        careData[@"images"] = nil;
    }
    
    //如果不需保存到本地 直接上传
    if (!local) {
        weakSelf_define;
        NSString *url;
        NSDictionary *params;
        switch (self.type) {
            case WCNCareRecordAddVCTypeEdit:{
                url = @"nursing/task/update";
                params = @{@"id":self.data[@"id"], @"detail":[NSString dataToJsonString:careData]};
            }
                break;
            case WCNCareRecordAddVCTypeAdd:{
                url = @"nursing/task/add";
                params = @{@"recordId":self.patient.stringId, @"detail":[NSString dataToJsonString:careData]};
            }
                break;
                
                
            default:
                break;
        }

    
        [[WCNetworkAccessManager sharedMg] POST:url parameters:params success:^(NSDictionary *result){
           
            if ( weakSelf.type == WCNCareRecordAddVCTypeAdd) {
                [MobClick event:AddWoundMaintenanceRecord];
            }else{
                 [MobClick event:MotifyWoundMaintenanceRecord];
            }
            
            for (UIViewController *vc in [weakSelf.navigationController viewControllers]) {
                if ([vc isKindOfClass:[WCNParentCareRecordVC class]]) {
                    
                    [weakSelf.navigationController popToViewController:vc animated:YES];
                }
            }
            //上传服务器成功 发送刷新通知
            [[NSNotificationCenter defaultCenter] postNotificationName:CareRecordsRefreshNotification object:nil];
        } failure:nil netError:nil always:^{
            [hud hide:YES];
        }];
        //保存到本地
    } else {
        if (self.type == WCNCareRecordAddVCTypeEdit) {
            return;
        }
        //保存数据到plist文件
        WCNPListFileDataStore *plistStore = [WCNPListFileDataStore shareStore];
        NSString *plistFileName = [NSString stringWithFormat:@"Nurse%@_Patient%@.plist", careData[@"uploadBy"], self.patient.stringId];
        NSString *path = [plistStore careUploadPath:plistFileName];
        NSMutableArray *careArray = [NSMutableArray array];
        if ([plistStore hasFile:path]) {
            careArray = [[plistStore readArrayFromFile:path] mutableCopy];
            for (int i = 0; i < careArray.count; i++) {
                NSMutableDictionary *muCareCacheItem = [NSMutableDictionary dictionaryWithDictionary:careArray[i]];
                [muCareCacheItem setValue:[NSNumber numberWithInt:i + 1] forKey:@"index"];
                [careArray replaceObjectAtIndex:i withObject:[muCareCacheItem copy]];
            }
            
        }
        careData[@"index"] = @0;
        [careArray insertObject:careData atIndex:0];
        [plistStore saveData:careArray toFile:path success:nil];
    }
}



#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 0) {
        if (buttonIndex == 1) {
            [self startUploadImages];
        } else {
            [self saveToLocal];
        }
    } else {
        if (alertView.tag == 1200) {
            return;
        }
        if (buttonIndex == 0) {
            if (self.hud) {
                [self.hud hide:YES];
            }
            if (_uploadTasks) {
                [self.uploadTasks enumerateObjectsUsingBlock:^(NSURLSessionDataTask * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (obj.state ==NSURLSessionTaskStateRunning) {
                        [obj cancel];
                    }
                }];
                [self.uploadTasks removeAllObjects];
            }
            
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 1200) {
        
        if (buttonIndex == 1) {
            UITextField *tf = [alertView textFieldAtIndex:0];
            [[NSNotificationCenter defaultCenter]removeObserver:self
                                                           name:@"UITextFieldTextDidChangeNotification"
                                                         object:tf];
            
            if ([tf.text length] > 0) {
                
                self.data[@"targetDay"] = tf.text;
                [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            }
        }
    }
}
#pragma mark - 中文输入时   限制输入字数
-(void)textFiledEditChanged:(NSNotification *)obj{
    UITextField *textField = (UITextField *)obj.object;
    
    NSString *toBeString = textField.text;
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > kMaxInputLength) {
                textField.text = [toBeString substringToIndex:kMaxInputLength];
            }
        }
        // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else{
            
        }
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else{
        if (toBeString.length > kMaxInputLength) {
            textField.text = [toBeString substringToIndex:kMaxInputLength];
        }
    }
}

#pragma mark -UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    if ([textField.text length] >= kMaxInputLength) {
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        if (existedLength - selectedLength + replaceLength >= kMaxInputLength) {
            return NO;
        }
    }
    
    return YES;
}


//添加药品
- (void)addDrugBtnClicked {
    if (!_drugs) {
        _drugs = [NSArray array];
    }
    if (!_careProductions) {
        NSArray *arr = @[@{@"medicineType":@1, @"name":@"药品", @"drugs":[NSArray array]},
                           @{@"medicineType":@2, @"name":@"敷料", @"drugs":[NSArray array]},
                           @{@"medicineType":@3, @"name":@"造口用物", @"drugs":[NSArray array]},
                           @{@"medicineType":@4, @"name":@"负压治疗", @"drugs":[NSArray array]}];
        _careProductions = [arr mutableCopy];
    }
    
    void(^selectDrug)(void) = ^{
        WSJTwoLevelPicker *picker = [[WSJTwoLevelPicker alloc] init];
        picker.title = @"选择护理用品";
        picker.dataArray = self.careProductions;
        picker.callBack = ^(NSInteger firstIndex, NSInteger secondIndex){
        
            NSDictionary *offerDrug = self.careProductions[firstIndex][@"drugs"][secondIndex];
            
            //检查药品是否重复添加
            for (NSDictionary *selectedDrug in self.drugs) {
                if ([offerDrug[@"id"] intValue] == [selectedDrug[@"id"] intValue]) {
                    [[WCPopupLayerManager shareMg] showTextOnly:@"已经选择了该药品" withView:self.view];
                    return;
                }
            }

            NSMutableArray *muDrugs = [NSMutableArray arrayWithArray:self.drugs];
            [muDrugs addObject:@{@"id":offerDrug[@"id"], @"name":offerDrug[@"name"],@"treatments":[NSArray array]}];
            _drugs = [muDrugs copy];
            [self.tableView reloadData];

        
        };
      
    };
    
    if (self.offerDrugs) {
        selectDrug();
    } else {
        MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:self.view];
        [[WCNetworkAccessManager sharedMg] POST:@"wound/medicine/list" parameters:nil success:^(NSDictionary *result){
            self.offerDrugs = result[@"data"];
            
            for (NSDictionary *dict in self.offerDrugs) {

                NSInteger index = [dict[@"medicineType"] integerValue] - 1;
                if (index < 0 | index > 3) {
                    return;
                }
                NSMutableDictionary *muProduct = [self.careProductions[index] mutableCopy];
                NSMutableArray *muArr = [muProduct[@"drugs"] mutableCopy];
                if (!muArr) {
                    muArr = [NSMutableArray array];
                }
                [muArr addObject:dict];
                muProduct[@"drugs"] = [muArr copy];
                self.careProductions[index] = muProduct;
                }
            selectDrug();
        } failure:nil netError:nil always:^{
            [hud hide:YES];
        }];
    }
}

//添加处理方式
- (void)addDrugDeal:(NSInteger)section {
    if (!self.offerDeals) {
        _offerDeals = [NSMutableDictionary dictionary];
    }
    //组装URL
    NSMutableArray *selectedDrugs = [NSMutableArray array];
    NSMutableString *url = [NSMutableString stringWithString:@"wound/treatments/"];
    NSString *key = [NSString stringWithFormat:@"%@",self.drugs[section - 1][@"id"]];
    if (key) {
        [url appendFormat:@"%d,", [key intValue]];
    }
    
    [url deleteCharactersInRange:NSMakeRange(url.length-1, 1)];
    
    void(^selectDeal)(void) = ^{
        
        WCPickerView *picker = [[WCPickerView alloc] init];
        picker.titleLabel.text = @"选择处理方案";
        //picker.numberOfComponents = 1;
        picker.pickerDataSource = self.offerDeals[key];
        // picker.secondPickerDataSource = self.offerDeals[self.selectedDrugs[0][@"id"]];
        
        //__weak typeof(picker) weakPicker = picker;
        
        
        picker.close = ^(NSInteger selected){
            NSArray *deals = self.offerDeals[key];
            if (!deals || deals.count == 0) {
                return;
            }
            NSDictionary *selectedDeal = deals[selected];
            
            //查询重复
            for (NSDictionary *deal in self.drugs[section - 1][@"treatments"]) {
                if ([deal[@"id"] intValue] == [selectedDeal[@"id"] intValue]) {
                    WSJSHOW(@"已经选择了这个处理方案");
                    return;
                }
            }
            
            NSMutableArray *muDrugs = [self.drugs mutableCopy];
            NSMutableArray *muDeals = [self.drugs[section - 1][@"treatments"] mutableCopy];
            NSMutableDictionary *muDic = [self.drugs[section - 1] mutableCopy];
            [muDeals addObject:selectedDeal];
            muDic[@"treatments"] = [muDeals copy];
            muDrugs[section - 1] = [muDic copy];
            self.drugs = [muDrugs copy];
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
        };
        
        [picker show:self.navigationController completion:nil];
    };
    
    if (self.offerDeals[key]) {
        selectDeal();
    } else {
        MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:self.view];
        [[WCNetworkAccessManager sharedMg] GET:url parameters:nil success:^(NSDictionary *result){
            self.selectedDrugs = selectedDrugs;
            [_offerDeals setObject:result[@"data"] forKey:key];
            self.getDealsUrl = url;
            
            selectDeal();
        } failure:nil netError:nil always:^{
            [hud hide:YES];
        }];
    }
}

- (void)addWoundDesc {
    defineWeakSelf;
    [JCAlertView showTwoButtonsWithTitle:@"提示" Message:@"通过伤口描述模板添加的内容直接覆盖原有伤口描述内容（伤口描述检索过来的描述信息）" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"取消" Click:nil ButtonType:JCAlertViewButtonTypeWarn ButtonTitle:@"确认" Click:^{
        WSJWoundDesVC *vc =[WSJWoundDesVC new];
        vc.callBackStr = ^(NSString *str){
            weakSelf.data[@"description"] = str;
            [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }];

}
#pragma mark - <UITableViewDataSource, UITableViewDelegate>
// 设置sectionHeader的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0 ) {
        return 0;
    }else if (section == self.drugs.count + 3 - 2){
    
        if (self.type == WCNCareRecordAddVCTypeScan) {
            return 15;
        }
        return 1;
    
    }else if (section == self.drugs.count + 3 - 1){
        
        return 15;
        
    }
    return 44;
}

//sectionHeader （标签）标题显示
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *sectionHeaderView = nil;
    if (!(section == 0 | section == self.drugs.count + 3 - 1 | section == self.drugs.count + 3 - 2)) {
        sectionHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
        sectionHeaderView.layer.borderColor = kBorderColor.CGColor;
        sectionHeaderView.layer.borderWidth = 0.5f;
        WCNWoundDrugView * headerView = [[[NSBundle mainBundle] loadNibNamed:@"WCNWoundDrugView" owner:nil options:0]lastObject];
        headerView.title.text = self.drugs[section - 1][@"name"];
        [headerView setBackgroundColor:[UIColor whiteColor]];
        if (self.type == WCNCareRecordAddVCTypeScan) {
            headerView.addBtn.hidden = YES;
            headerView.deleteBtn.hidden = YES;
        }
        headerView.addOrDeleteBlock = ^(BOOL isAdd){
                if (isAdd) {
                    [self addDrugDeal:section];
                }else {
                    [JCAlertView showTwoButtonsWithTitle:@"提示" Message:@"确认删除护理用品，该删除将会删除所有的处理方式" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"取消" Click:nil ButtonType:JCAlertViewButtonTypeWarn ButtonTitle:@"确认" Click:^{
                        

                        NSMutableArray *muDrugs = [NSMutableArray arrayWithArray:self.drugs];
                        [muDrugs removeObjectAtIndex:section - 1];
                        _drugs = [muDrugs copy];
                        [tableView reloadData];
                    }];
                }
        };
        [sectionHeaderView addSubview:headerView];
    }
    return sectionHeaderView;
//    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 15)];
//    headView.backgroundColor = [UIColor blueColor];
//    return headView;
}
// 设置SectioFooter的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        if (self.type == WCNCareRecordAddVCTypeScan) {
            if (self.drugs.count == 0) {
                return kOnePX;
            }
        }
        return 30;
    }else if (section == self.drugs.count+1) {
    
        if (self.type == WCNCareRecordAddVCTypeScan) {
            return kOnePX;
        }
        return 44;
    }
    return kOnePX;
}

//SectioFooterView
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView *v = nil;
    
    if (section == 0) {
        if (self.type == WCNCareRecordAddVCTypeScan) {
            if (self.drugs.count == 0) {
                return v;
            }
        }
        v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
        [v setBackgroundColor:kAppBg];
//        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 15)];
//        line.backgroundColor = kAppBg;
//        [v addSubview:line];
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, 13, kScreenWidth-10, 12)];
        
        title.font = [UIFont systemFontOfSize:15];
        title.text = @"护理用品";
        title.textColor = kTxtColor;
        if (self.type == WCNCareRecordAddVCTypeScan) {
            v.userInteractionEnabled = NO;
        }
        [v addSubview:title];
        return v;
    }else if(section == self.drugs.count + 3 - 2){
        if (self.type == WCNCareRecordAddVCTypeScan) {
//            v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kOnePX)];
//            [v setBackgroundColor:[UIColor redColor]];
            return v;
        }
        v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
        [v setBackgroundColor:[UIColor whiteColor]];
        UIButton *addDrugBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [addDrugBtn setFrame:CGRectMake(10, 0, 120, 44)];
        [addDrugBtn setImage:[UIImage imageNamed:@"添加药品"] forState:UIControlStateNormal];
        [addDrugBtn setTitle:@"添加护理用品" forState:UIControlStateNormal];
        [addDrugBtn setImageEdgeInsets:UIEdgeInsetsMake(10, 0, 10, 120 - 24)];
        [addDrugBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -30, 0, -20)];
        [addDrugBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
        [addDrugBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [addDrugBtn addTarget:self action:@selector(addDrugBtnClicked) forControlEvents:UIControlEventTouchUpInside];
        [v addSubview:addDrugBtn];
        
        return v;
    }

    
    return v;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.type == WCNCareRecordAddVCTypeScan) {
        
        if (indexPath.section ==0 &&indexPath.row ==2) {
            WCNMulTextEditVC *vc = [[WCNMulTextEditVC alloc] initWithType:WCNMulTextEditSave];
            vc.title = @"伤口描述";
            vc.textViewPlaceholder = @"请填写伤口描述";
            vc.textViewValue = self.data[@"description"];
            vc.canEmpty = YES;
            vc.unAbleEdit = YES;
//            vc.callback = ^(NSString *text){
//                weakSelf.data[@"description"] = text;
//                [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//            };
            [self.navigationController pushViewController:vc animated:YES];
          
        }
        
        return;
    }
    
    defineWeakSelf;
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 1:{
                NSUInteger index = 0;
                NSMutableArray *days = [NSMutableArray array];
                for (int i=1; i<=100; i++) {
                    if ([self.data[@"targetDay"] intValue] == i) {
                        index = i-1;
                    }
                    [days addObject:[NSString stringWithFormat:@"%d", i]];
                }
                UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"" message:@"请输入天数" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                alert.alertViewStyle = UIAlertViewStylePlainTextInput;
                alert.delegate = self;
                alert.tag = 1200;
                UITextField *tf = [alert textFieldAtIndex:0];
                tf.delegate = self;
                [[NSNotificationCenter defaultCenter] addObserver:weakSelf selector:@selector(textFiledEditChanged:)
                                                             name:@"UITextFieldTextDidChangeNotification"
                                                           object:tf];
                //设置输入框的键盘类型
                tf.keyboardType = UIKeyboardTypeNumberPad;
                [alert show];
            }
                break;
                
            case 2:{
                WCNMulTextEditVC *vc = [[WCNMulTextEditVC alloc] initWithType:WCNMulTextEditSave];
                vc.title = @"伤口描述";
                vc.textViewPlaceholder = @"请填写伤口描述";
                vc.textViewValue = self.data[@"description"];
                vc.canEmpty = YES;
                vc.callback = ^(NSString *text){
                    weakSelf.data[@"description"] = text;
                    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                };
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            default:
                break;
        }
    } else if (indexPath.section == self.drugs.count + 2) {
        if (indexPath.row == 0) {
            WCNMulTextEditVC *vc = [[WCNMulTextEditVC alloc] initWithType:WCNMulTextEditSave];
            vc.title = @"备注";
            vc.textViewPlaceholder = @"请填写备注";
            vc.textViewValue = self.data[@"note"];
            vc.canEmpty = YES;
            vc.callback = ^(NSString *text){
                weakSelf.data[@"note"] = text;
                [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            };
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *tCell;
    if (indexPath.section == 0) {
       
        
        switch (indexPath.row) {
            case 0: {
                WCNMulTextTCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
                cell.arowImg.hidden = YES;
                cell.mulText.textAlignment = NSTextAlignmentRight;
                cell.mulText.numberOfLines = 1;
                cell.textTitle.text = @"伤口部位";
                cell.mulText.text = self.data[@"bodyPartName"];
                tCell = cell;
                break;
            }
            case 1: {
                WCNMulTextTCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
                cell.arowImg.hidden = NO;
                cell.mulText.textAlignment = NSTextAlignmentRight;
                cell.mulText.numberOfLines = 1;
                cell.textTitle.text = @"伤口天数";
                if (self.data[@"targetDay"]) {
                    cell.mulText.text = [NSString stringWithFormat:@"Day%@", self.data[@"targetDay"]];
                } else {
                    cell.mulText.text = @"";
                }
                tCell = cell;
                break;
            }
            case 2: {
                //                cell.textTitle.text = @"伤口描述";
                //                cell.mulText.textAlignment = NSTextAlignmentLeft;
                //                cell.mulText.numberOfLines = 0;
                //                cell.mulText.text = self.data[@"description"];
                //                [cell.mulText showAttributedText:0 lineSpace:5];
                WCNAddWoundDesCell *wcell = [tableView dequeueReusableCellWithIdentifier:@"WCNAddWoundDesCell"];
                wcell.contentL.text = self.data[@"description"];
                
                if (self.type == WCNCareRecordAddVCTypeScan) {
                    wcell.btn.hidden =YES;
                    wcell.btnHeight.constant = 0;
                
                }else{
                    wcell.btn.hidden =NO;
                    wcell.btnHeight.constant = 28;
                }
                weakSelf_define;
                wcell.click =^(){
                    [weakSelf addWoundDesc];
                };
                tCell = wcell;
                break;
            }
        }
    }else if (indexPath.section == self.drugs.count + 3 - 1) {
        
            WCNMulTextTCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
            cell.mulText.textAlignment = NSTextAlignmentRight;
            cell.textTitle.text = @"备注";
            cell.mulText.textAlignment = NSTextAlignmentLeft;
            cell.mulText.numberOfLines = 0;
            cell.arowImg.hidden = NO;
            cell.mulText.text = self.data[@"note"];
            [cell.mulText showAttributedText:0 lineSpace:5];
            
            tCell = cell;
        
    }else if (indexPath.section == self.drugs.count + 3 - 2) {
        if (self.type == WCNCareRecordAddVCTypeScan) {
            WCNMulTextTCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
            cell.mulText.textAlignment = NSTextAlignmentRight;
            cell.textTitle.text = @"备注";
            cell.mulText.textAlignment = NSTextAlignmentLeft;
            cell.mulText.numberOfLines = 0;
            cell.mulText.text = self.data[@"note"];
            [cell.mulText showAttributedText:0 lineSpace:5];
           cell.arowImg.hidden = NO;
            tCell = cell;
            
        }
    }else {
    
        WCNWoundDealCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId4];
        if (self.type == WCNCareRecordAddVCTypeScan) {
//            cell.deleBtn.hidden = YES;
        }
        cell.deleteDeal = ^{
            NSMutableDictionary *muDict = [self.drugs[indexPath.section - 1] mutableCopy];
            NSMutableArray *muarr = [muDict[@"treatments"] mutableCopy];
            [muarr removeObjectAtIndex:indexPath.row];
            muDict[@"treatments"] = [muarr copy];
            NSMutableArray *muDrugs = [self.drugs mutableCopy];
            muDrugs[indexPath.section - 1] = [muDict copy];
            self.drugs = [muDrugs copy];
            [tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
            
        };
        cell.contentText.text = self.drugs[indexPath.section - 1][@"treatments"][indexPath.row][@"name"];
        return cell;
    
    }
    
    [tCell setSeparatorInset:UIEdgeInsetsZero];
    if ([tCell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [tCell setPreservesSuperviewLayoutMargins:NO];
    }
    if ([tCell respondsToSelector:@selector(setLayoutMargins:)]) {
        [tCell setLayoutMargins:UIEdgeInsetsZero];
    }
    
    return tCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.section == 0 ) {
        if (indexPath.row == 2) {
            
            CGFloat h = [tableView fd_heightForCellWithIdentifier:@"WCNAddWoundDesCell" configuration:^(WCNAddWoundDesCell *cell) {
                
                cell.contentL.text = self.data[@"description"];
                //                [cell.mulText showAttributedText:0 lineSpace:5];
            }];
            if (self.type == WCNCareRecordAddVCTypeScan) {
              return MAX(kOnePX+h -28, 116.0-28);
            }
            return MAX(kOnePX+h, 116.0);
        }
        return 45;
        
    }  else if (indexPath.section == self.drugs.count + 2) {
            CGFloat h = [tableView fd_heightForCellWithIdentifier:cellId configuration:^(WCNMulTextTCell *cell) {
            cell.mulText.text = self.data[@"note"];
            [cell.mulText showAttributedText:0 lineSpace:5];
            }];
            return MAX(kOnePX+h, 45.0);
    
    }else if (indexPath.section == self.drugs.count + 1) {
        if (self.type == WCNCareRecordAddVCTypeScan) {
            CGFloat h = [tableView fd_heightForCellWithIdentifier:cellId configuration:^(WCNMulTextTCell *cell) {
                cell.mulText.text = self.data[@"note"];
                [cell.mulText showAttributedText:0 lineSpace:5];
            }];
            return MAX(kOnePX+h, 45.0);
        }
            return 0;
        
    }else {
        CGFloat h = [tableView fd_heightForCellWithIdentifier:cellId4 configuration:^(WCNWoundDealCell *cell) {

        cell.contentText.text = self.drugs[indexPath.section - 1][@"treatments"][indexPath.row][@"name"];
        }];
        return MAX(kOnePX+h, 45.0);
    }
    
    return 45;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 3;
    } else if (section == self.drugs.count + 3 - 1) {
        return 1;
    }else if (section == self.drugs.count + 3 - 2) {
        if (self.type == WCNCareRecordAddVCTypeScan) {
            return 1;
        }
        return 0;
    }else {
       return [self.drugs[section - 1][@"treatments"] count];
    }
    return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.type == WCNCareRecordAddVCTypeScan) {
        return self.drugs.count + 2;
    }
    return self.drugs.count + 3;
}




@end
